package com.sinping.qh.service.admin.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.collect.Lists;
import com.sinping.qh.api.exception.HandlerException;
import com.sinping.qh.api.support.*;
import com.sinping.qh.domain.auth.Role;
import com.sinping.qh.domain.auth.User;
import com.sinping.qh.domain.auth.UserRole;
import com.sinping.qh.domain.common.UnitDomain;
import com.sinping.qh.domain.lab.LaboratoryDomain;
import com.sinping.qh.domain.user.ContentInfo;
import com.sinping.qh.domain.user.TokenInfo;
import com.sinping.qh.domain.user.UserInfo;
import com.sinping.qh.domain.user.UserLaboratory;
import com.sinping.qh.dto.admin.lab.ApiUnitAndLabDto;
import com.sinping.qh.dto.admin.lab.UnitLabTreeDto;
import com.sinping.qh.dto.admin.user.ApiUserDto;
import com.sinping.qh.dto.admin.user.ApiUserInfolistDto;
import com.sinping.qh.dto.admin.user.ApiUserManagerUnitAndLabDto;
import com.sinping.qh.dto.auth.UserSessionDTO;
import com.sinping.qh.query.base.QueryParams;
import com.sinping.qh.query.lab.LaboratoryQuery;
import com.sinping.qh.query.lab.UserLaboratoryQuery;
import com.sinping.qh.query.user.UserInfoQuery;
import com.sinping.qh.repository.mongo.UnitRepository;
import com.sinping.qh.repository.mongo.lab.LaboratoryRepository;
import com.sinping.qh.repository.mongo.user.ContentInfoRepository;
import com.sinping.qh.repository.mongo.user.TokenRepository;
import com.sinping.qh.repository.mongo.user.UserInfoRepository;
import com.sinping.qh.repository.mongo.user.UserLaboratoryRepository;
import com.sinping.qh.service.MongoManager;
import com.sinping.qh.service.admin.IAddorEditUserService;
import com.sinping.qh.service.auth.IRoleService;
import com.sinping.qh.service.auth.ISessionService;
import com.sinping.qh.service.auth.IUserRoleService;
import com.sinping.qh.service.auth.IUserService;
import com.sinping.qh.service.common.CommonDbConst;
import com.sinping.qh.service.redis.RedisCommon;
import com.sinping.qh.service.redis.RedisService;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.misc.IdGenerator;
import com.sinping.qh.utils.security.CryptoUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author Tiansx
 * @create 2018-05-28 18:51
 **/
@Service
public class IAddorEditUserServiceImpl implements IAddorEditUserService {
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private UnitRepository unitRepository;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserRoleService userRoleService;
    @Qualifier("sessionServiceRedisImpl")
    @Autowired
    private ISessionService iSessionService;
//    @Qualifier("sessionMongoServiceRedisImpl")
//    @Autowired
//    private ISessionMongoService iSessionMongoService;
    @Autowired
    private UserLaboratoryRepository userLaboratoryRepository;
    @Autowired
    private LaboratoryRepository laboratoryRepository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    MongoManager mongoManager;
    @Autowired
    TokenRepository tokenRepository;
    @Autowired
    RedisService redisService;

    @Autowired
    ContentInfoRepository contentInfoRepository;


    private final static Logger logger = LoggerFactory.getLogger(IAddorEditUserServiceImpl.class);

    @Override
    public ResDto addUser(HttpServletRequest httpRequest, ApiUserDto apiuserDTO) {
        /**
         * 获取当前用户id
         */
        String token = httpRequest.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        if (userSessionDTO == null) {
            return new ResDto(Const.PARAM_ERROR, "用户未登录");
        }

        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }
        //设置创建人id
        apiuserDTO.setCreateUserId(userSessionDTO.getId());


        try {
            UserInfo userInfoOne = userInfoRepository.findByUserName(apiuserDTO.getUserName());
            if (userInfoOne != null) {
                return new ResDto(Const.SERVER_ERROR, "该用户名已存在");
            }
            //验证创建人是否存在
            UserInfo userInfoOneCreateUser = userInfoRepository.findOne(apiuserDTO.getCreateUserId());
            if (userInfoOneCreateUser == null) {
                return new ResDto(Const.SERVER_ERROR, "该创建人不存在");
            }

            //MongoDB数据源
            UserInfo userInfo = BeanMapper.map(apiuserDTO, UserInfo.class);
            userInfo.setId(IdGenerator.uuid2());
            userInfo.setUpdateUserId(apiuserDTO.getCreateUserId());

            //查询数据库时检查有没有存储随机盐值
            ContentInfo contentInfo=contentInfoRepository.findContentInfoByUserId(userInfo.getId());
            String saltStr="";
            byte[] salt=null;
            if(contentInfo!=null){
                //如果有则获取随机盐值
                saltStr=contentInfo.getSalt();
                salt= Base64Utils.decodeFromString(saltStr);
//                contentInfo.setGmtModified(new Date());
            }
            else{
                //生成随机盐值
                contentInfo=new ContentInfo();
                contentInfo.setId(IdGenerator.uuid2().toString());
                contentInfo.setUserId(userInfo.getId());
                salt= CryptoUtil.createSalt();
                contentInfo.setSalt(Base64Utils.encodeToString(salt));
                contentInfo.setGmtCreated(new Date());
                contentInfo.setGmtModified(new Date());
                contentInfoRepository.save(contentInfo);
            }

            userInfo.setContent(CryptoUtil.sha256(salt,getCustomString(apiuserDTO.getUserName())));

//            userInfo.setContent(UserContentUtils.createHash(getCustomString(apiuserDTO.getUserName())));
            /*** 根据roleid查询角色名称后存入user*/
            boolean inserRole = false;
            if (StringUtils.isNotBlank(apiuserDTO.getRoleId())) {
                Role role = roleService.selectById(apiuserDTO.getRoleId());
                if (role == null) {
                    return new ResDto(Const.SERVER_ERROR, "角色不存在");
                }
                inserRole = true;
                userInfo.setRoleName(role.getRole());
                userInfo.setPermission(role.getPermission());
            }
            userInfo.setTelephone(userInfo.getTelephone());
            if (StringUtils.isNotBlank(apiuserDTO.getUnitId())) {
                UnitDomain one = unitRepository.findOne(apiuserDTO.getUnitId());
                if (one == null) {
                    return new ResDto(Const.SERVER_ERROR, "单位不存在");
                }
                userInfo.setUnitName(one.getUnitName());
            }

            userInfo.setGmtCreated(new Date());
            userInfo.setGmtModified(new Date());


            //Mysql数据源   用于获取用户角色和权限

            User user = BeanMapper.map(userInfo, User.class);
            user.setId(userInfo.getId());
            user.setRoleid(userInfo.getRoleId());
            user.setUsername(userInfo.getUserName());
            user.setNickname(userInfo.getFullName());
            //0：正常  1：删除
            user.setDeleted(0);
            user.setStatus(0);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());

            UserInfo save = userInfoRepository.save(userInfo);
            if (save == null) {
                return new ResDto(Const.SERVER_ERROR, "生成用户记录失败");
            }

            /***新用户入库*/
            boolean insert = userService.insert(user);
            if (!insert) {
                userInfoRepository.delete(userInfo.getId());
                return new ResDto(Const.SERVER_ERROR, "mysql生成用户记录失败");
            }
            /***插入角色关联表*/
            if (inserRole) {
                UserRole userRole = new UserRole();
                userRole.setId(IdGenerator.uuid2());
                userRole.setUserId(user.getId());
                userRole.setRoleId(user.getRoleid());
                boolean insert1 = userRoleService.insert(userRole);
                if (!insert1) {
                    userInfoRepository.delete(userInfo.getId());
                    userService.deleteById(user.getId());
                    return new ResDto(Const.SERVER_ERROR, "角色关联失败");
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("添加用户异常");
            logger.error(e.getMessage(), e);
        }


        return new ResDto(Const.SUCCESS, "添加用户成功");
    }

    @Override
    public ResDto updateUser(HttpServletRequest httpRequest, ApiUserDto apiuserDTO) {

        /**
         * 获取当前用户id
         */
        String token = httpRequest.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        if (userSessionDTO == null) {
            return new ResDto(Const.PARAM_ERROR, "用户未登录");
        }

        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }
        //设置修改人id
        apiuserDTO.setUpdateUserId(userSessionDTO.getId());


        try {
            UserInfo userInfoOne = null;
            UserInfo userInfoDB=null;
            if (StringUtils.isNotBlank(apiuserDTO.getId())) {
                userInfoOne = userInfoRepository.findOne(apiuserDTO.getId());
                if (userInfoOne == null) {
                    return new ResDto(Const.SERVER_ERROR, "用户信息不存在");
                }
                userInfoDB = BeanMapper.map(userInfoOne, UserInfo.class);
            }
            if (StringUtils.isNotBlank(apiuserDTO.getUpdateUserId())) {
                UserInfo one = userInfoRepository.findOne(apiuserDTO.getUpdateUserId());
                if (one == null) {
                    return new ResDto(Const.SERVER_ERROR, "更新人不存在");
                }
            }

            UserInfo userInfoExist = userInfoRepository.findByUserName(apiuserDTO.getUserName());
            if (userInfoExist != null ) {
                if (!userInfoExist.getId().equals(apiuserDTO.getId())){
                    return new ResDto(Const.SERVER_ERROR, "该用户名已存在");
                }

            }

            if (StringUtils.isNotBlank(apiuserDTO.getUnitId())) {
                UnitDomain one = unitRepository.findOne(apiuserDTO.getUnitId());
                if (one == null) {
                    return new ResDto(Const.SERVER_ERROR, "单位不存在");
                }
                userInfoOne.setUnitName(one.getUnitName());
            }

            /*** 根据roleid查询角色名称r*/
            boolean updateRole = false;
            if (StringUtils.isNotBlank(apiuserDTO.getRoleId())) {
                Role role = roleService.selectById(apiuserDTO.getRoleId());
                if (role == null) {
                    return new ResDto(Const.SERVER_ERROR, "角色不存在");
                }
                updateRole = true;
                userInfoOne.setRoleName(role.getRole());
                userInfoOne.setPermission(role.getPermission());
            }
            /**
             * 复制更新信息到mongo
             */

            userInfoOne.setFullName(apiuserDTO.getFullName());
            userInfoOne.setTelephone(apiuserDTO.getTelephone());
            userInfoOne.setEmail(apiuserDTO.getEmail());
            userInfoOne.setRoleId(apiuserDTO.getRoleId());
            userInfoOne.setUnitId(apiuserDTO.getUnitId());
            userInfoOne.setUpdateUserId(userSessionDTO.getId());
            userInfoOne.setGmtModified(new Date());

            /**
             * 复制更新信息到MySql
             */
            User user = new User();
            user.setId(userInfoOne.getId());
            user.setRoleid(userInfoOne.getRoleId());
            user.setRolename(userInfoOne.getRoleName());
            user.setUsername(userInfoOne.getUserName());
            user.setNickname(userInfoOne.getFullName());
            user.setUpdateTime(new Date());


            /***更新用户库*/
            boolean update = userService.updateById(user);
            if (!update) {
                return new ResDto(Const.SERVER_ERROR, "mysql生成用户记录失败");
            }
            /***更新角色关联表*/
            if (updateRole) {
                List<UserRole> rolseByUserIdList = userRoleService.getRolseByUserId(user.getId());
                if (rolseByUserIdList == null) {

                    /***用户没有关联的角色，插入角色关联表*/
                    if (updateRole) {
                        UserRole userRole = new UserRole();
                        userRole.setId(IdGenerator.uuid2());
                        userRole.setUserId(user.getId());
                        userRole.setRoleId(user.getRoleid());
                        boolean insert1 = userRoleService.insert(userRole);
                        if (!insert1) {
                            return new ResDto(Const.SERVER_ERROR, "角色关联失败");
                        }
                    }

                } else {
                    /***用户有关联的角色,更新角色关联表*/
                    UserRole userRole = rolseByUserIdList.get(0);
                    userRole.setRoleId(user.getRoleid());
                    userRole.setUpdateTime(new Date());
                    boolean update1 = userRoleService.updateById(userRole);
                    if (!update1) {
                        return new ResDto(Const.SERVER_ERROR, "更新角色关联失败");
                    }

                }
            }

            UserInfo save = userInfoRepository.save(userInfoOne);
            if (save == null) {
                return new ResDto(Const.SERVER_ERROR, "用户记录更新失败");
            }

            List<UserLaboratory> allByUserId = userLaboratoryRepository.findAllByUserId(save.getId());
            for (UserLaboratory userLaboratory : allByUserId) {
                userLaboratory.setFullName(save.getFullName());
                userLaboratory.setTelephone(save.getTelephone());
                userLaboratory.setRoleId(save.getRoleId());
            }
            userLaboratoryRepository.save(allByUserId);
            //设置app redis缓存更新
            TokenInfo tokenInfoByUserId = tokenRepository.findTokenInfoByUserId(save.getId());
            if (tokenInfoByUserId!=null){
                //修改了用户角色
                if (!userInfoDB.getRoleId().equals(apiuserDTO.getRoleId())){
                    /***app token*/
                    redisService.expireKey(RedisCommon.RedisPrimaryKey.UserSessionByApp.getFirstKey()+tokenInfoByUserId.getToken());
                    /***删除后台session*/
                    iSessionService.deleteSessionAndTokenByUserid(save.getId());

                }else {
                    redisService.setUpdate(RedisCommon.RedisPrimaryKey.UserSessionByApp.getFirstKey()+tokenInfoByUserId.getToken());
                }

            }



        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户记录更新异常：{}", e);
            return new ResDto(Const.SERVER_ERROR, "用户记录更新异常");
        }


        return new ResDto(Const.SUCCESS, "用户记录更成功");
    }

    @Override
    public ResDto deleteUser(String id) {
        try {
            UserInfo userInfoOne = null;
            if (StringUtils.isNotBlank(id)) {
                userInfoOne = userInfoRepository.findOne(id);
                if (userInfoOne == null) {
                    return new ResDto(Const.SERVER_ERROR, "用户信息不存在");
                }
            }
            List<UserRole> rolseByUserIdList = userRoleService.getRolseByUserId(id);
            if (!rolseByUserIdList.isEmpty()) {
                boolean delete = userRoleService.deleteById(rolseByUserIdList.get(0).getId());
                if (!delete) {
                    return new ResDto(Const.SERVER_ERROR, "删除用户角色关联失败");
                }
            }

            User user = userService.selectById(id);
            if (user != null) {
                boolean delete = userService.deleteById(id);
                if (!delete) {
                    return new ResDto(Const.SERVER_ERROR, "删除MySql用户记录失败");

                }
            }
            //删除用户负责表该用户记录
            List<UserLaboratory> allByUserId = userLaboratoryRepository.findAllByUserId(id);
            userLaboratoryRepository.delete(allByUserId);
            /***删除后台session*/
            iSessionService.deleteSessionAndTokenByUserid(user.getId());
            /** 删除app token*/
            TokenInfo tokenInfoByUserId = tokenRepository.findTokenInfoByUserId(user.getId());
            if (tokenInfoByUserId != null) {
//                iSessionMongoService.deleteSessionByToken(tokenInfoByUserId.getToken());
                redisService.expireKey(RedisCommon.RedisPrimaryKey.UserSessionByApp.getFirstKey()+tokenInfoByUserId.getToken());
            }

            userInfoRepository.delete(id);


        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除用户信息异常：{}", e);
            return new ResDto(Const.SERVER_ERROR, "删除用户信息异常");
        }

        return new ResDto(Const.SUCCESS, "删除成功");
    }

    @Override
    public ResDto getUserDetail(String id) {
        UserInfo userInfoOne = null;
        if (StringUtils.isNotBlank(id)) {
            userInfoOne = userInfoRepository.findOne(id);
            if (userInfoOne == null) {
                return new ResDto(Const.SERVER_ERROR, "用户信息不存在");
            }
        }
        ApiUserDto apiUserDto = BeanMapper.map(userInfoOne, ApiUserDto.class);

        if (apiUserDto == null) {
            return new ResDto(Const.SERVER_ERROR, "获取用户信息失败");
        }
        String data = JsonMapper.defaultMapper().toJson(apiUserDto);
        return new ResDto(ConstEum.SUCCESS, data);

    }

    @Override
    public ResDto getUserList(HttpServletRequest request, FrontPage page) {
        /**
         * 获取当前用户id
         */
        String token = request.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        if (userSessionDTO == null) {
            return new ResDto(Const.PARAM_ERROR, "用户未登录");
        }
        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {
            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }

        List<UserLaboratory> userManagerUnitList = getUserManagerUnit(userSessionDTO.getId(),CommonDbConst.DB_DELETE_NORMAL);
        List<String> unitIdList = null;
        //TODO 宋志涛 显示所有用户，不区分院校
//        for (UserLaboratory userLaboratory : userManagerUnitList) {
//            unitIdList.add(userLaboratory.getManagerUnitId());
//        }
        Integer pageSize = page.getSize();
        Integer pageNum = page.getPage();
        UserInfoQuery userInfoQuery;
        ApiUserInfolistDto dto = null;
        //2.Map conditionMap
        Map<String, Object> conditionMap = page.getCondition();
        if (null == conditionMap || conditionMap.isEmpty()) {
            //return new ResDto(Const.PARAM_ERROR, "条件参数为空或有不正确的数据格式");
            //查询所有的记录
            //5.得到 NoticeBookQuery
            userInfoQuery = new UserInfoQuery();
        } else {
            //3.Map conditionMap=>String conditionJson
            String conditionJson = JsonMapper.defaultMapper().toJson(conditionMap);
            //4.String conditionJson=> NoticeBookDto dto
            dto = JsonMapper.defaultMapper().fromJson(conditionJson, ApiUserInfolistDto.class);
            //5.NoticeBookDto dto=> NoticeBookQuery noticeBookQuery
            userInfoQuery = BeanMapper.map(dto, UserInfoQuery.class);
        }
        /**属于当前登录用户负责院系的用户*/
        if (userInfoQuery.getUnitId() == null) {
            userInfoQuery.setUnitIdList(unitIdList);
        }

        String order = "DESC";
        if (!StringUtils.isEmpty(page.getOrder())) {
            if ("ASC".equals(page.getOrder().toUpperCase())) {
                order = "ASC";
            }
        }
        String prop = "gmt_modified";
        if (!StringUtils.isEmpty(page.getProp())) {
            prop = page.getProp();
        }
        //设置查询条件
        Pageable pageRequest = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.fromString(order), prop));
        List<ApiUserInfolistDto> apiUserInfolist;
        List<UserInfo> userListPage;
        List<UserInfo> userList;
        //负责院系不为空查用户负责表
        if (dto.getManagerUnitName() != null) {
            UserLaboratoryQuery userLaboratoryQuery = new UserLaboratoryQuery();
            userLaboratoryQuery.setStatus(CommonDbConst.DB_DELETE_NORMAL);
            userLaboratoryQuery.setType(CommonDbConst.USER_MANAGER_UNIT);
            userLaboratoryQuery.setManagerUnitName(dto.getManagerUnitName());
            userLaboratoryQuery.setUserName(dto.getUserName());
            userLaboratoryQuery.setFullName(dto.getFullName());
//            userLaboratoryQuery.setManagerUnitId(dto.getUnitId());
            List<UserLaboratory> userLaboratoryListPage = findUser(unitIdList, dto, pageRequest, userLaboratoryQuery, UserLaboratory.class, UserLaboratory.class);
            List<UserLaboratory> userLaboratoryList = findUser(unitIdList, dto, null, userLaboratoryQuery, UserLaboratory.class, UserLaboratory.class);
            userListPage = new ArrayList<>();
            for (UserLaboratory userLaboratory : userLaboratoryListPage) {
                UserInfo one = userInfoRepository.findOne(userLaboratory.getUserId());
                if (one != null) {
                    userListPage.add(one);
                }

            }
            userList = BeanMapper.mapList(userLaboratoryList, UserInfo.class);

        } else {
            //负责院系为空查用户信息表
            userListPage = findUser(unitIdList, dto, pageRequest, userInfoQuery, UserInfo.class, UserInfo.class);
            userList = findUser(unitIdList, dto, null, userInfoQuery, UserInfo.class, UserInfo.class);
        }

        apiUserInfolist = BeanMapper.mapList(userListPage, ApiUserInfolistDto.class);

        for (ApiUserInfolistDto userInfo : apiUserInfolist) {
            //负责的院系
            List<UserLaboratory> units = userLaboratoryRepository.findAllByUserIdAndType(userInfo.getId(), CommonDbConst.USER_MANAGER_UNIT);
            userInfo.setManagerUnitList(units);
            //负责的实验室
            List<UserLaboratory> labs = userLaboratoryRepository.findAllByUserIdAndType(userInfo.getId(), CommonDbConst.USER_MANAGER_LAB);
            userInfo.setManagerLabList(labs);
        }

        ResDto resDto = new ResDto(ConstEum.SUCCESS);

        Page<ApiUserInfolistDto> pagesResult = new PageImpl<>(apiUserInfolist, pageRequest, userList.size());
        ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(resDto, pagesResult, ApiUserInfolistDto.class, page);

        return resDto;
    }

    public <T> List<T> findUser(List<String> loginUserMangerUnitIdList, ApiUserInfolistDto dto, Pageable pageRequest, QueryParams userParams, Class<?> clazz, Class<T> targetClazz) {
        try {
            List<AggregationOperation> operations = Lists.newArrayList();
            Criteria one = mongoManager.where(userParams);
            operations.add(Aggregation.match(one));
            if (dto.getManagerUnitName() != null) {
                LookupOperation lookupOperation
                        = LookupOperation.newLookup()
                        .from("tb_user_info")
                        .localField("user_id")
                        .foreignField("_id")
                        .as("userInfo");

                operations.add(lookupOperation);
                if (dto.getUnitId() != null) {
                    Criteria unitId = Criteria.where("userInfo.unit_id").is(dto.getUnitId());
                    operations.add(Aggregation.match(unitId));
                } else {
                    Criteria unitIdList = Criteria.where("userInfo").ne(new HashSet<>()).and("userInfo.unit_id").in(loginUserMangerUnitIdList);
                    operations.add(Aggregation.match(unitIdList));
                }

            }

            if (pageRequest != null) {
                SortOperation sortOperation = new SortOperation(pageRequest.getSort());
                operations.add(sortOperation);
                SkipOperation skipOperation = new SkipOperation(pageRequest.getOffset());
                operations.add(skipOperation);
                LimitOperation limitOperation = new LimitOperation(pageRequest.getPageSize());
                operations.add(limitOperation);

            }


            Aggregation aggregation = Aggregation.newAggregation(operations);


            String table = template.getCollectionName(clazz);
            AggregationResults<T> results = template.aggregate(aggregation, table, targetClazz);


            return results.getMappedResults();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public ResDto getUserManagerUnit(HttpServletRequest httpRequest, String userId,String status) {
        /**
         * 获取当前用户id
         */
        String token = httpRequest.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        if (userSessionDTO == null) {
            return new ResDto(Const.PARAM_ERROR, "操作用户未登录");
        }

        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取操作用户id失败");
        }
        /**
         * 用户负责的院系
         */
        List<UserLaboratory> userManagerUnitList = getUserManagerUnit(userId,status);

        String data = JsonMapper.defaultMapper().toJson(userManagerUnitList);

        return new ResDto(ConstEum.SUCCESS, data);
    }

    @Override
    public ResDto getAllLabList() {
        //单位类型 0：校级  1：院系
        //用户负责的类型：0：院系 1：实验室
        /**
         * 全部院系
         */
        List<UnitDomain> unitDomainList = unitRepository.findAllByUnitTypeAndStatus(CommonDbConst.UNIT_TYPE_YUAN, CommonDbConst.DB_DELETE_NORMAL);
        /**
         * 全部实验室
         */
        List<LaboratoryDomain> laboratoryDomainList = laboratoryRepository.findAllByStatus(CommonDbConst.DB_DELETE_NORMAL, new Sort(Sort.Direction.ASC ,"building_name","room_no"));

        ApiUserManagerUnitAndLabDto apiUserManagerUnitAndLabDto = new ApiUserManagerUnitAndLabDto();
//        apiUserManagerUnitAndLabDto.setAllUnitList(unitDomainList);

        /**
         * 构建实验室层级树
         */
        List<UnitLabTreeDto> apiallLabTreeList = new ArrayList<>();
        for (UnitDomain unit : unitDomainList) {
            /**
             * 所有实验室层级
             */
            UnitLabTreeDto unitLabTreeDto = new UnitLabTreeDto(unit);
            List<LaboratoryDomain> children = new ArrayList<>();
            for (LaboratoryDomain lab : laboratoryDomainList) {
                if (CommonDbConst.UNIT_TYPE_YUAN.equals(unit.getUnitType()) && lab.getUnitId().equals(unit.getId())) {
                    children.add(lab);

                }

            }
            unitLabTreeDto.setChildren(children);
            if (!unitLabTreeDto.getChildren().isEmpty()) {
                apiallLabTreeList.add(unitLabTreeDto);

            }

            //所有实验室
            apiUserManagerUnitAndLabDto.setAllLabList(apiallLabTreeList);
        }
        String data = JsonMapper.defaultMapper().toJson(apiUserManagerUnitAndLabDto);
        return new ResDto(ConstEum.SUCCESS, data);
    }

    public <T> List<T> findUserManagerLab(String id, Class<?> clazz, Class<T> targetClazz) {
        List<AggregationOperation> operations = Lists.newArrayList();
        LaboratoryQuery laboratoryQuery = new LaboratoryQuery();
        laboratoryQuery.setUnitId(id);
        Criteria one = mongoManager.where(laboratoryQuery);
        operations.add(Aggregation.match(one));

        GraphLookupOperation graphLookupOperation = GraphLookupOperation.builder()
                .from("tb_lab")
                .startWith("unit_id")
                .connectFrom("unit_id")
                .connectTo("id")
                .as("children");
        operations.add(graphLookupOperation);

        Aggregation aggregation = Aggregation.newAggregation(operations);
        String table = template.getCollectionName(clazz);
        AggregationResults<T> results = template.aggregate(aggregation, table, targetClazz);


        return results.getMappedResults();
    }


    @Override
    public ResDto getUserManagerLabList(HttpServletRequest httpRequest, String userId) {
        /**
         * 获取当前用户id
         */
        String token = httpRequest.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        if (userSessionDTO == null) {
            return new ResDto(Const.PARAM_ERROR, "操作用户未登录");
        }

        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取操作用户id失败");
        }
        /**
         * 全部院系
         */
        List<UnitDomain> unitDomainList = unitRepository.findAllByUnitType(CommonDbConst.UNIT_TYPE_YUAN);
        //单位类型 0：校级  1：院系
        //用户负责的类型：0：院系 1：实验室
//        /**
//         * 用户负责的院系
//         */
//        List<UserLaboratory> userManagerUnitList = getUserManagerUnit(userId);

        /**
         * 用户负责的实验室
         */
        List<UserLaboratory> userManagerLabList = getUserManagerLab(userId);

        ApiUserManagerUnitAndLabDto apiUserManagerUnitAndLabDto = new ApiUserManagerUnitAndLabDto();

//        apiUserManagerUnitAndLabDto.setUserManagerUnitList(userManagerUnitList);

        /**
         * 构建实验室层级树
         */
        List<UnitLabTreeDto> apiUserManagerLabTreeList = new ArrayList<>();
        for (UnitDomain unit : unitDomainList) {

            /**
             * 用户负责层级
             */
            UnitLabTreeDto managerUnitLabTreeDto = new UnitLabTreeDto(unit);
            List<UserLaboratory> managerChildren = new ArrayList<>();
            for (UserLaboratory lab : userManagerLabList) {
                if (CommonDbConst.UNIT_TYPE_YUAN.equals(unit.getUnitType()) && lab.getManagerUnitId().equals(unit.getId()) && CommonDbConst.USER_MANAGER_LAB.equals(lab.getType())
                        && userId.equals(lab.getUserId())) {

                    managerChildren.add(lab);
                }

            }
            if (!managerChildren.isEmpty()) {
                managerUnitLabTreeDto.setManagerChildren(managerChildren);

            }
            if (managerUnitLabTreeDto.getManagerChildren() != null) {
                apiUserManagerLabTreeList.add(managerUnitLabTreeDto);
            }


        }

        //清除无用户负责实验室的数据
        for (UnitLabTreeDto unitLabTreeDto : apiUserManagerLabTreeList) {
            if (unitLabTreeDto.getManagerChildren() == null) {
                apiUserManagerLabTreeList.remove(unitLabTreeDto);
            }
        }

        //用户负责的实验室
        apiUserManagerUnitAndLabDto.setUserManagerLabList(apiUserManagerLabTreeList);


        String data = JsonMapper.defaultMapper().toJson(apiUserManagerUnitAndLabDto);


        return new ResDto(ConstEum.SUCCESS, data);
    }

    /**
     * 单选展开院系下实验室 * 备用
     */
    @Override
    public ResDto getLabListByUnitId(String unitId) {
        if (!StringUtils.isEmpty(unitId)) {
            UnitDomain one = unitRepository.findOne(unitId);
            if (one == null) {
                return new ResDto(Const.SERVER_ERROR, "实验室所属单位不存在，请刷新界面后重试");
            }
        }

        /**
         * 全部院系
         */
        List<UnitDomain> unitDomainList = unitRepository.findAllByUnitType(CommonDbConst.UNIT_TYPE_YUAN);

        ApiUserManagerUnitAndLabDto apiUserManagerUnitAndLabDto = new ApiUserManagerUnitAndLabDto();

        /**
         * 构建实验室层级树
         */
        List<UnitLabTreeDto> apiallLabTreeList = new ArrayList<>();
        for (UnitDomain unit : unitDomainList) {

            /**所有实验室层级*/
            UnitLabTreeDto unitLabTreeDto = new UnitLabTreeDto(unit);
            if (!StringUtils.isEmpty(unitId)) {
                if (unitId.equals(unit.getId())) {
                    /**查找院系下的实验室*/
                    List<LaboratoryDomain> children = findUserManagerLab(unit.getId(), LaboratoryDomain.class, LaboratoryDomain.class);
                    unitLabTreeDto.setChildren(children);
                }
            }
            List<LaboratoryDomain> allLabByUnitIdList = laboratoryRepository.findAllByUnitId(unit.getId());
            if (!allLabByUnitIdList.isEmpty()) {
                apiallLabTreeList.add(unitLabTreeDto);
            }

            //所有实验室
            apiUserManagerUnitAndLabDto.setAllLabList(apiallLabTreeList);
        }
        String data = JsonMapper.defaultMapper().toJson(apiUserManagerUnitAndLabDto);
        return new ResDto(ConstEum.SUCCESS, data);
    }

    @Override
    public ResDto addUnitToUser(HttpServletRequest httpRequest, ApiUnitAndLabDto apiUnitAndLabDto) {
        UserInfo user = userInfoRepository.findOne(apiUnitAndLabDto.getUser_id());
        if (user == null) {
            return new ResDto(Const.SERVER_ERROR, "用户不存在");
        }
        for (String managerUnitId : apiUnitAndLabDto.getManagerUnitIdList()) {
            UnitDomain unit = unitRepository.findOne(managerUnitId);
            if (unit == null) {
                return new ResDto(Const.SERVER_ERROR, "单位不存在");
            }

            UserLaboratory allByUserIdAndType = userLaboratoryRepository.findByUserIdAndManagerUnitIdAndType(user.getId(), managerUnitId, CommonDbConst.USER_MANAGER_UNIT);
            if (allByUserIdAndType != null) {
                return new ResDto(Const.SERVER_ERROR, unit.getUnitName() + "与用户关系已存在");
            }


        }

        for (String managerUnitId : apiUnitAndLabDto.getManagerUnitIdList()) {

            UnitDomain unit = unitRepository.findOne(managerUnitId);
            UserLaboratory save = setManagerUnitInfo(user, unit);
            if (save == null) {
                return new ResDto(Const.SERVER_ERROR, "配置过程中出错");
            }


        }

        return new ResDto(ConstEum.SUCCESS, "配置成功");


    }


    @Override
    public ResDto addLabToUser(HttpServletRequest request, ApiUnitAndLabDto apiUnitAndLabDto) {
        UserInfo user = userInfoRepository.findOne(apiUnitAndLabDto.getUser_id());
        if (user == null) {
            return new ResDto(Const.SERVER_ERROR, "用户不存在");
        }
        //校验单位是否存在
        for (ApiUnitAndLabDto apiUnitAndLabDto1:apiUnitAndLabDto.getList()) {
            UnitDomain unit = unitRepository.findOne(apiUnitAndLabDto1.getManagerUnitId());
            if (unit == null) {
                return new ResDto(Const.SERVER_ERROR, "单位不存在");
            }
        }

        //校验实验是否存在，实验室归属单位是否存在

        for (ApiUnitAndLabDto apiUnitAndLabDto1:apiUnitAndLabDto.getList()) {
            for (String managerLabId : apiUnitAndLabDto1.getManagerLabIdList()) {
                LaboratoryDomain lab = laboratoryRepository.findOne(managerLabId);
                if (lab == null) {
                    return new ResDto(Const.SERVER_ERROR, "有实验室id不存在");
                }

                if (!lab.getUnitId().equals(apiUnitAndLabDto1.getManagerUnitId())) {
                    return new ResDto(Const.SERVER_ERROR, lab.getLabName() + "：归属单位不正确");
                }
                UserLaboratory byManagerLabId = userLaboratoryRepository.findByManagerLabIdAndUserIdAndType(managerLabId, user.getId(), CommonDbConst.USER_MANAGER_LAB);
                if (byManagerLabId != null) {
                    return new ResDto(Const.SERVER_ERROR, lab.getLabName() + "：实验室用户关系已存在");
                }


            }
        }


        for (ApiUnitAndLabDto apiUnitAndLabDto1:apiUnitAndLabDto.getList()) {
            UnitDomain unit = unitRepository.findOne(apiUnitAndLabDto1.getManagerUnitId());
            if (unit != null) {
                for (String str: apiUnitAndLabDto1.getManagerLabIdList()) {
                    UserLaboratory save = setUserManagerLabInfo(user, unit, str);
                    if (save == null) {
                        return new ResDto(Const.SERVER_ERROR, "配置过程中出错");
                    }

                }
            }
        }

        return new ResDto(ConstEum.SUCCESS, "配置成功");
    }

    @Override
    public ResDto deleteUnitToUser(HttpServletRequest request, ApiUnitAndLabDto apiUnitAndLabDto) {
        UserInfo user = userInfoRepository.findOne(apiUnitAndLabDto.getUser_id());
        if (user == null) {
            return new ResDto(Const.SERVER_ERROR, "用户不存在");
        }
        if (CommonDbConst.USER_ID.equals(user.getId())) {
            return new ResDto(Const.SERVER_ERROR, "系统初始化用户，不允许此操作");
        }
        for (String managerUnitId : apiUnitAndLabDto.getManagerUnitIdList()) {
            UserLaboratory userUnit = null;

            userUnit = userLaboratoryRepository.findByUserIdAndManagerUnitIdAndType(user.getId()
                    , managerUnitId, CommonDbConst.USER_MANAGER_UNIT);
            if (userUnit == null) {
                return new ResDto(Const.SERVER_ERROR, "用户院系关系不存在");
            }
        }

        for (String managerUnitId : apiUnitAndLabDto.getManagerUnitIdList()) {
            UserLaboratory userUnit = null;
            userUnit = userLaboratoryRepository.findByUserIdAndManagerUnitIdAndType(user.getId()
                    , managerUnitId, CommonDbConst.USER_MANAGER_UNIT);
            if (userUnit != null) {
                userLaboratoryRepository.delete(userUnit.getId());
            }

        }

        return new ResDto(Const.SUCCESS, "删除成功");
    }

    @Override
    public ResDto deleteLabToUser(HttpServletRequest request, ApiUnitAndLabDto apiUnitAndLabDto) {
        UserInfo user = userInfoRepository.findOne(apiUnitAndLabDto.getUser_id());
        if (user == null) {
            return new ResDto(Const.SERVER_ERROR, "用户不存在");
        }

        for (ApiUnitAndLabDto apiUnitAndLabDto1:apiUnitAndLabDto.getList()) {
            for (String managerLabId : apiUnitAndLabDto1.getManagerLabIdList()) {
                UserLaboratory userLab = userLaboratoryRepository.findByUserIdAndManagerUnitIdAndManagerLabIdAndType(user.getId()
                        , apiUnitAndLabDto1.getManagerUnitId(), managerLabId, CommonDbConst.USER_MANAGER_LAB);
                if (userLab == null) {
                    return new ResDto(Const.SERVER_ERROR, "用户实验室关系不存在");
                }
            }
        }


        //删除负责的实验室

        for (ApiUnitAndLabDto apiUnitAndLabDto1:apiUnitAndLabDto.getList()) {
            for (String managerLabId : apiUnitAndLabDto1.getManagerLabIdList()) {
                UserLaboratory userLab = userLaboratoryRepository.findByUserIdAndManagerUnitIdAndManagerLabIdAndType(user.getId()
                        , apiUnitAndLabDto1.getManagerUnitId(), managerLabId, CommonDbConst.USER_MANAGER_LAB);
                if (userLab != null) {
                    userLaboratoryRepository.delete(userLab.getId());
                }

            }
        }

        return new ResDto(Const.SUCCESS, "删除成功");
    }

    @Override
    public ResDto getRoleList() {
        Wrapper<Role> wrapper = new EntityWrapper<>();
        List<Role> roles = roleService.selectList(wrapper);
        String data = JsonMapper.defaultMapper().toJson(roles);
        return new ResDto(ConstEum.SUCCESS, data);
    }

    @Override
    public List<UserInfo> findUserByRoleId(Role role,Role roleDB) {
        List<UserInfo> allUserList = userInfoRepository.findAllByRoleId(role.getId());
        for (UserInfo userInfo : allUserList) {
            userInfo.setRoleName(role.getRole());
            userInfo.setPermission(role.getPermission());

            TokenInfo tokenInfoByUserId = tokenRepository.findTokenInfoByUserId(userInfo.getId());
            //若app权限修改
            if (!role.getPermission().equals(roleDB.getPermission())){
                /** 删除app缓存 token*/
                if (tokenInfoByUserId != null) {
                    redisService.expireKey(RedisCommon.RedisPrimaryKey.UserSessionByApp.getFirstKey()+tokenInfoByUserId.getToken());
                }
            }else if (tokenInfoByUserId!=null){
                //更新app缓存
                redisService.setUpdate(RedisCommon.RedisPrimaryKey.UserSessionByApp.getFirstKey()+tokenInfoByUserId.getToken());
            }

        }
        userInfoRepository.save(allUserList);

        return allUserList;
    }

//
//    /**
//     * 用户负责的院系
//     */
//    public List<UserLaboratory> getUserManagerUnit(UserSessionDTO userSessionDTO) {
//
//        List<UserLaboratory> userManagerUnitList = userLaboratoryRepository.findAllByUserIdAndTypeOrderByGmtCreatedDesc(userSessionDTO.getId(), "0");
//        return userManagerUnitList;
//    }

    /**
     * 用户负责的院系
     */
    public List<UserLaboratory> getUserManagerUnit(String userId,String status) {
        List<UserLaboratory> userManagerUnitList;
        if (CommonDbConst.DB_DELETE_NORMAL.equals(status)){
            userManagerUnitList= userLaboratoryRepository.findAllByUserIdAndTypeAndStatusOrderByGmtCreatedDesc
                    (userId, CommonDbConst.USER_MANAGER_UNIT,CommonDbConst.DB_DELETE_NORMAL);
           }else {
            userManagerUnitList = userLaboratoryRepository.findAllByUserIdAndTypeOrderByGmtCreatedDesc(userId, CommonDbConst.USER_MANAGER_UNIT);
        }

        return userManagerUnitList;
    }

//    /**
//     * 用户负责的实验室
//     */
//    public List<UserLaboratory> getUserManagerLab(UserSessionDTO userSessionDTO) {
//        List<UserLaboratory> userManagerLabList = userLaboratoryRepository.findAllByUserIdAndTypeOrderByGmtCreatedDesc(userSessionDTO.getId(), "1");
//        return userManagerLabList;
//    }

    /**
     * 用户负责的实验室
     */
    public List<UserLaboratory> getUserManagerLab(String userId) {
        List<UserLaboratory> userManagerLabList = userLaboratoryRepository.findAllByUserIdAndTypeOrderByLabBuildingNameAscManagerRoomNoAsc(userId, CommonDbConst.USER_MANAGER_LAB);
        return userManagerLabList;
    }

    @Override
    public ResDto deleteUnitAndLabToUser(HttpServletRequest httpRequest, ApiUnitAndLabDto apiUnitAndLabDto) {

        UserInfo user = userInfoRepository.findOne(apiUnitAndLabDto.getUser_id());
        if (user == null) {
            return new ResDto(Const.SERVER_ERROR, "用户不存在");
        }

        UserLaboratory userUnit = null;
        if (CommonDbConst.USER_MANAGER_UNIT.equals(apiUnitAndLabDto.getType())) {
            userUnit = userLaboratoryRepository.findByUserIdAndManagerUnitIdAndType(user.getId()
                    , apiUnitAndLabDto.getManagerUnitId(), CommonDbConst.USER_MANAGER_UNIT);
            if (userUnit == null) {
                return new ResDto(Const.SERVER_ERROR, "用户院系关系不存在");
            }
        }


        if (CommonDbConst.USER_MANAGER_LAB.equals(apiUnitAndLabDto.getType())) {
            for (String managerLabId : apiUnitAndLabDto.getManagerLabIdList()) {
                UserLaboratory userLab = userLaboratoryRepository.findByUserIdAndManagerUnitIdAndManagerLabIdAndType(user.getId()
                        , apiUnitAndLabDto.getManagerUnitId(), managerLabId, CommonDbConst.USER_MANAGER_LAB);
                if (userLab == null) {
                    return new ResDto(Const.SERVER_ERROR, "用户实验室关系不存在");
                }
            }
        }
        //删除负责的院系
        if (CommonDbConst.USER_MANAGER_UNIT.equals(apiUnitAndLabDto.getType())) {
            userLaboratoryRepository.deleteByUserIdAndManagerUnitIdAndType(user.getId(), userUnit.getManagerUnitId(), CommonDbConst.USER_MANAGER_UNIT);
        }
        //删除负责的实验室
        if (CommonDbConst.USER_MANAGER_LAB.equals(apiUnitAndLabDto.getType())) {
            for (String managerLabId : apiUnitAndLabDto.getManagerLabIdList()) {
                UserLaboratory userLab = userLaboratoryRepository.findByUserIdAndManagerUnitIdAndManagerLabIdAndType(user.getId()
                        , apiUnitAndLabDto.getManagerUnitId(), managerLabId, CommonDbConst.USER_MANAGER_LAB);
                if (userLab != null) {
                    userLaboratoryRepository.deleteByUserIdAndManagerUnitIdAndManagerLabIdAndType(user.getId()
                            , userUnit.getManagerUnitId(), userLab.getManagerLabId(), CommonDbConst.USER_MANAGER_LAB);
                }

            }

        }

        return new ResDto(Const.SUCCESS, "删除成功");
    }


    private UserLaboratory setUserManagerLabInfo(UserInfo user, UnitDomain unit, String managerLabId) {
        LaboratoryDomain lab = laboratoryRepository.findOne(managerLabId);
        UserLaboratory userLaboratory = new UserLaboratory();
        userLaboratory.setId(IdGenerator.uuid2());
        userLaboratory.setUserId(user.getId());
        userLaboratory.setUserName(user.getUserName());
        userLaboratory.setFullName(user.getFullName());
        userLaboratory.setTelephone(user.getTelephone());
        userLaboratory.setRoleId(user.getRoleId());
        userLaboratory.setManagerUnitId(unit.getId());
        userLaboratory.setManagerUnitName(unit.getUnitName());
//        userLaboratory.setType(apiUnitAndLabDto.getType());
        userLaboratory.setType(CommonDbConst.USER_MANAGER_LAB);
        userLaboratory.setStatus(lab.getStatus());
        userLaboratory.setGmtCreated(new Date());
        userLaboratory.setGmtModified(new Date());
        userLaboratory.setManagerLabId(managerLabId);
        userLaboratory.setManagerLabName(lab.getLabName());
        userLaboratory.setManagerRoomNo(lab.getRoomNo());
        userLaboratory.setLabBuildingId(lab.getBuildingId());
        userLaboratory.setLabBuildingName(lab.getBuildingName());
        return userLaboratoryRepository.save(userLaboratory);
    }

    private UserLaboratory setManagerUnitInfo(UserInfo user, UnitDomain unit) {
        UserLaboratory userLaboratory = new UserLaboratory();
        userLaboratory.setId(IdGenerator.uuid2());
        userLaboratory.setUserId(user.getId());
        userLaboratory.setUserName(user.getUserName());
        userLaboratory.setFullName(user.getFullName());
        userLaboratory.setTelephone(user.getTelephone());
        userLaboratory.setRoleId(user.getRoleId());
        userLaboratory.setManagerUnitId(unit.getId());
        userLaboratory.setManagerUnitName(unit.getUnitName());
//        userLaboratory.setType(apiUnitAndLabDto.getType());
        userLaboratory.setType(CommonDbConst.USER_MANAGER_UNIT);
        userLaboratory.setStatus(unit.getStatus());
        userLaboratory.setGmtCreated(new Date());
        userLaboratory.setGmtModified(new Date());
        return userLaboratoryRepository.save(userLaboratory);
    }


    /**
     * 生成默认密码或重置密码
     */
    public static String getCustomString(String userName) {
        String result = userName+"000000";
        if (!StringUtils.isNotBlank(userName)) {
            return result;
        }
        if (userName.length() <= 6) {
            userName = userName + "000000";
            result = StringUtils.substring(userName, 0, 6);
            return result;
        }
        if (userName.length() >= 15) {
            result = StringUtils.substring(userName, 0, 15);
            return result;
        }
        result = userName;
        return result;

    }

    /**
     * 获取用户负责的实验室或院系集合
     * @param userId
     * @param type     0：负责院系   1:负责实验室
     * @return
     */
    public List<String> getUserManagerUnitIdOrLabIdList(String userId,String type) {
        //已经配置实验室的院系，在院系配置中要删除
        List<String> handleUnitIDLists = new ArrayList<>();
        //查询所负责实验室
        List<String> labIDLists = new ArrayList<>();
        //查询所负责院系
        List<String> unitIDLists = new ArrayList<>();
        //当前登录用户
        if (!StringUtils.isEmpty(userId)) {
            List<UserLaboratory> labList = userLaboratoryRepository.findAllByUserIdAndType(userId, CommonDbConst.USER_MANAGER_LAB);
            if (!labList.isEmpty() && labList.size() > 0) {
                for (int i = 0; i < labList.size(); i++) {
                    labIDLists.add(labList.get(i).getManagerLabId());
                    handleUnitIDLists.add(labList.get(i).getManagerUnitId());
                }
            }

            List<UserLaboratory> unitList = userLaboratoryRepository.findAllByUserIdAndType(userId, CommonDbConst.USER_MANAGER_UNIT);
            if (!unitList.isEmpty() && unitList.size() > 0) {
                for (int i = 0; i < unitList.size(); i++) {

                    if (!handleUnitIDLists.isEmpty() && handleUnitIDLists.size() > 0) {
                        if (!handleUnitIDLists.contains(unitList.get(i).getManagerUnitId())) {
                            unitIDLists.add(unitList.get(i).getManagerUnitId());
                        }
                    } else {
                        unitIDLists.add(unitList.get(i).getManagerUnitId());
                    }

                }
            }


        }
        if (CommonDbConst.USER_MANAGER_UNIT.equals(type)){
            return unitIDLists;
        }else {
            return labIDLists;
        }

    }

}





